import random

from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django import forms

from djangoProject3 import settings
from web import models
from utils.tencent.sms import send_sms_single
from django_redis import get_redis_connection
from utils import encrypt


class RegisterModelForm(forms.ModelForm):
    password = forms.CharField(label='密码', widget=forms.PasswordInput(), min_length=6, max_length=18, error_messages={
        'min_length': '密码长度不能小于6个字符',
        'max_length': '密码长度不能大于64个字符',
    })
    confirm_password = forms.CharField(label='重复密码', widget=forms.PasswordInput(), min_length=6, max_length=18,
                                       error_messages={
                                           'min_length': '重复密码长度不能小于6个字符',
                                           'max_length': '重复密码长度不能大于64个字符', })
    code = forms.CharField(label='验证码', widget=forms.TextInput())
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误')])

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def clean_username(self):
        # 用户名钩子
        username = self.cleaned_data.get('username')
        exists = models.UserInfo.objects.filter(username=username).exists()
        if exists:
            raise ValidationError('用户名已存在')
        return username

    def clean_email(self):
        email = self.cleaned_data.get('email')
        exists = models.UserInfo.objects.filter(email=email).exists()
        if exists:
            raise ValidationError('邮箱已存在')
        return email

    def clean_password(self):

        pwd = self.cleaned_data.get('password')
        return encrypt.md5(pwd)

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get('password')
        confirm_password = encrypt.md5(self.cleaned_data.get('confirm_password'))
        if pwd != confirm_password:
            raise ValidationError('密码不一致')
        return confirm_password

    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data.get('mobile_phone')
        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).exists()
        if exists:
            raise ValidationError('手机号已注册')
        return mobile_phone

    def clean_code(self):
        code = self.cleaned_data.get('code')
        mobile_phone = self.cleaned_data.get('mobile_phone')
        if not mobile_phone:
            return code
        conn = get_redis_connection()
        redis_code = conn.get(mobile_phone)
        if not redis_code:
            raise ValidationError('验证码失效或未发生，请重新发送')
        redis_str_code = redis_code.decode('utf-8')
        if code.strip() != redis_str_code.strip():
            raise ValidationError('验证码输入错误')
        return code


class SendSmsForm(forms.Form):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_mobile_phone(self):
        """ 手机号校验的钩子 """
        mobile_phone = self.cleaned_data['mobile_phone']
        # 判断短信模板是否有问题
        tpl = self.request.GET.get('tpl')
        template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
        if not template_id:
            # self.add_error('mobile_phone','短信模板错误')
            raise ValidationError('短信模板错误')

        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).exists()
        if tpl == 'login':
            if not exists:
                raise ValidationError('手机号不存在')
        else:
            # 校验数据库中是否已有手机号
            if exists:
                raise ValidationError('手机号已存在')

        code = random.randrange(1000, 9999)
        # 发送短信
        if tpl == 'login':
            sms = send_sms_single(mobile_phone, template_id, [code, ])
        else:
            sms = send_sms_single(mobile_phone, template_id, [code, 5])
        if sms['result'] != 0:
            raise ValidationError("短信发送失败，{}".format(sms['errmsg']))
        # 验证码 写入redis（django-redis）
        conn = get_redis_connection()
        conn.set(mobile_phone, code, ex=300)
        return mobile_phone


class LoginSMSForm(forms.Form):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误')])
    code = forms.CharField(label='验证码', widget=forms.TextInput())

    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data.get('mobile_phone')
        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        if not user_object:
            return ValidationError('手机号不存在')
        return user_object

    def clean_code(self):
        code = self.cleaned_data.get('code')
        user_object = self.cleaned_data.get('mobile_phone')
        if not user_object.mobile_phone:
            return code
        conn = get_redis_connection()
        redis_code = conn.get(user_object.mobile_phone)
        if not redis_code:
            raise ValidationError('验证码失效或未发送，请重新发送')
        redis_str_code = redis_code.decode('utf-8')
        if code.strip() != redis_str_code.strip():
            raise ValidationError('验证码舒服错误，请重新输入')
        return code


class LoginForm(forms.Form):
    username = forms.CharField(label='用户名/手机号/邮箱')
    password = forms.CharField(label='密码', min_length=6, max_length=18, widget=forms.PasswordInput(render_value=True))
    # render_value=True 输出密码后点击登录密码不会消失
    code = forms.CharField(label='图片验证码')

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_code(self):
        # 读取用户输入的验证码
        code = self.cleaned_data.get('code')
        session_code = self.request.session.get('image_code')
        if not session_code:
            raise ValidationError('验证码已过期')
        if code.strip().upper() != session_code.strip().upper():
            raise ValidationError('验证码输入错误')
        return code

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return encrypt.md5(pwd)
